package com.zhanghe;

import com.zhanghe.protocol.serializer.SerializerAlgorithm;
import com.zhanghe.protocol.serializer.SerializerManager;
import com.zhanghe.protocol.v1.Command;
import com.zhanghe.wzq.command.CommandType;
import com.zhanghe.wzq.command.request.*;
import com.zhanghe.wzq.command.response.CreateTableResponse;
import com.zhanghe.wzq.command.response.LoginResponse;
import com.zhanghe.wzq.command.response.OneStepResponse;
import com.zhanghe.wzq.command.response.StartGameResponse;
import com.zhanghe.wzq.handler.WebSocketServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Server
 *
 * @author Clevo
 * @date 2018/12/13
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {
        SerializerManager.setDefault(SerializerAlgorithm.JSON);
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Command.rigester(CommandType.LOGIN_REQUEST,LoginRequest.class);
        Command.rigester(CommandType.LOGIN_RESPONSE,LoginResponse.class);
        Command.rigester(CommandType.CREATE_TABLE_REQUEST,CreateTableRequest.class);
        Command.rigester(CommandType.CREATE_TABLE_RESPONSE,CreateTableResponse.class);
        Command.rigester(CommandType.START_GAME_REQUEST,StartGameRequest.class);
        Command.rigester(CommandType.START_GAME_RESPONSE,StartGameResponse.class);
        Command.rigester(CommandType.JOIN_TABLE_REQUEST,JoinTableRequest.class);
        Command.rigester(CommandType.ONE_STEP_REQUEST,OneStepRequest.class);
        Command.rigester(CommandType.ONE_STEP_RESPONSE,OneStepResponse.class);

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new WebSocketServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8989).sync();
            channelFuture.channel().closeFuture().sync();
        }finally{
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
